package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.MaterielListAdapter;
import com.glory.brepda.adapter.PartListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.EqpBody;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.MaterielListEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: DAWorkBeginActivity
 * Author: XJH
 * Date: 2020/5/21 9:05
 * Description:开始作业DA工序
 * History:
 */
public class DAWorkBeginActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvLotTMatCount)
    TextView tvLotTMatCount;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvPartList)
    RecyclerView rvPartList;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.eqpScan)
    ImageView eqpScan;
    // 框架二维码扫描输入框
    FreeUI_ClearEditText etRlfInfo;

    // 料盒相关配置
    // 料盒扫描框
    FreeUI_ClearEditText etCarrier;
    // 装载料盒信息容器
    RecyclerView rvCarrierList;
    // 容器适配器
    private AddCarrierDataAdapter carrierAdapter;

    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private MaterielListAdapter materielListAdapter;
    private List<MaterielListEntity.Materiel> materielList;
    private List<MaterielListEntity.Materiel> partList;
    private PartListAdapter partListAdapter;
    private String woid;
    private LotInfoEntity lotInfoBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_da;
    }

    @Override
    protected void initView() {
        initLayout();

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(DAWorkBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    if(StringUtils.isNotEmpty(response.getTip())){
                        ShowDialog.showDialog(DAWorkBeginActivity.this,response.getTip(),"制程风险提示");
                    }
                    if(response.getPART().getUDF().getcarRules().toString().equals("Y")){
                        ShowDialog.showDialog(DAWorkBeginActivity.this,"该批次为车规产品，请按车规要求规范生产！","提示：");
                    }
                    lotInfoBean = response;
                    Constant.LIMITPACKAGETYPEQTY = response.getLIMITPACKAGETYPEQTY();
                    Constant.PACKAGETYPE = response.getPACKAGETYPE();
                    Constant.WIRESPEC = response.getWIRESPEC();
                    Constant.BDCODE = response.getBD_CODE();
                    Constant.PARTNAME = response.getLOT().getPARTNAME();
                    woid = response.getLOT().getWOID();
                    etEqpWorkID.requestFocus();
                    tvPauseStatus.setText(response.getLOT().getHOLDSTATE());
                    tvBDNum.setText(response.getWIRINGNO());
                    tvTitle.setText("开始作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    tvLotState.setText(response.getLOT().getSTATE());
                    tvLotTMatCount.setText(response.getLOT().getUDF().gettMatCount());
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }

            });
        });

        initEdit(etEqpWorkID, s -> {
            partList.clear();
            materielList.clear();
            getWqpInfo(s);
            // 框架输入框获取焦点
            MyUtils.editTextRequestFocus(etRlfInfo);
        });
        // 初始化扫描框
        etRlfInfo = findViewById(R.id.etRlfInfo);

        // 初始化料盒扫描框扫描事件
        initEdit(etCarrier, s -> {
            if (StringUtils.isEmpty(s)) {
                return;
            }

            // 控制操作顺序，理论上也可以不要
            if (lotInfoBean == null) {
                showToast("请先扫描批次", false);
                return;
            }

            // 判断列表中是否已经含有料盒信息
            if (carrierAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            // 输入框添加相关料盒数据
            carrierAdapter.addData(s);
            // 清空输入的信息，并获取焦点
            etCarrier.setText(StringUtils.EMPTY);
            MyUtils.editTextRequestFocus(etCarrier);
        });
    }

    private void getWqpInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpEntity>>
                (new TypeToken<BaseResponseBean<EqpEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(DAWorkBeginActivity.this, true, getSupportFragmentManager())) {
                    EqpEntity body = response.body().getResponse().getBody();
                    materielListAdapter.setNewData(body.equipmentlist);
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<EqpEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTKITTING");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "EQPBYID");
        EqpBody eqpBody = new EqpBody("",eqpID,"");
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(eqpBody)).getAsJsonObject());
        NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", DAWorkBeginActivity.this, map, callBack);
    }

//    private void getKittingInfo(String eqpID) {
//        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
//                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
//                }.getType(), getSupportFragmentManager(), this) {
//
//            @Override
//            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
//                super.onSuccess(response);
//                if (response.body().isSuccess(DAWorkBeginActivity.this,true,getSupportFragmentManager())){
//                    List<MaterielListEntity.Materiel> mlotlist = response.body().getResponse().getBody().getMLOTLIST();
//                    for (MaterielListEntity.Materiel data : mlotlist){
//                        if (data.getMATERIALTYPE().equals("WAFER")){
//                            partList.add(data);
//                        }else {
//                            materielList.add(data);
//                        }
//                    }
//                    materielListAdapter.setNewData(materielList);
//                    partListAdapter.setNewData(partList);
//                }
//
//            }
//
//            @Override
//            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
//                super.onError(response);
//                loadError(response.getException(),"MLOTKITTING");
//
//            }
//        };
//        JsonObject map = new JsonObject();
//        map.addProperty("ACTIONTYPE","LOAD");
//        map.addProperty("EQUIPMENTID",eqpID);
//        NetUtils.requestPostNet("MES.MLOTKITTING","MLOTKITTING",DAWorkBeginActivity.this,map,callBack);
//    }


    private void initLayout() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        listTv1.setText("No.");
        listTv2.setText("芯片料号");
        listTv3.setText("芯片批号");
        listTv4.setText("芯片片号");
        setMainLayout(llMain);
        etLot.requestFocus();
        initRecyclerView(rvMaterielList,this);
        initRecyclerView(rvPartList,this);

        materielListAdapter = new MaterielListAdapter(null);
        materielListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielListAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielListAdapter);

        partListAdapter = new PartListAdapter(null);
        partListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        partListAdapter.isFirstOnly(true);
        rvPartList.setAdapter(partListAdapter);

        materielList = new ArrayList<>();
        partList = new ArrayList<>();

        // 初始化料盒输入配置
        etCarrier = findViewById(R.id.etMaterielBox);
        rvCarrierList = findViewById(R.id.rvMaterielBoxList);
        // 初始化信息容器，初始化适配器。信息容器使用适配器
        initRecyclerView(rvCarrierList, this);
        carrierAdapter = getCarrierAdapter();
        rvCarrierList.setAdapter(carrierAdapter);

    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        eqpScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etEqpWorkID.setText(qrResult);
                        break;
                }
            }

        }

    }



    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {

//        if (actionControl("Submit01")){
//            return;
//        }
        if (lotInfoBean == null) {
            showConfirmDialog("批次未扫描或批次不存在，请确认");
            return;
        }

        if (tvLotState.getText().toString().equals("待投产")){
            showConfirmDialog("批次未投产，请联系计划部执行投产");
            return;
        }

        if (tvLotState.getText().toString().equals("正在作业")){
            showConfirmDialog("批次正在作业，请直接操作出站功能");
            return;
        }

        lotInfoBean.setFRAME_INFO(getText(etRlfInfo));
        // 25/7/14 901713 DA开始作业新增料盒输入框，将料盒信息传递到后台
        LotUtils.lotTrackIn(getSupportFragmentManager(),lotInfoBean, carrierAdapter.getData(), woid,"DBLOTTRACKIN",this,getText(etEqpWorkID),getText(etLot),new ArrayList<String>(),"DefaultTrackIn");
    }

}
